package com.vn.toaa.tintinscreenoff;

import android.app.Activity;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.os.Vibrator;
import android.preference.PreferenceManager;

import com.vn.tooa.screenoff.R;

public class MainActivity extends Activity {

	public static final String TAG = MainActivity.class.getSimpleName();
	protected static final int REQUEST_ENABLE = 0;
	public static final int MAX_TRY_LOCK_NUMBER = 10;

	private DevicePolicyManager mDevicePolicyManager;
	private ComponentName mAdminComponent;
	private int mTryNumber = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// handle case that user pressed OPEN button after installing app
		if (!isTaskRoot()) {
			final Intent intent = getIntent();
			final String intentAction = intent.getAction();
			if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && intentAction != null
					&& intentAction.equals(Intent.ACTION_MAIN)) {
				finish();
				return;
			}
		}
		
		startService(new Intent(this, ScreenService.class));

		mAdminComponent = new ComponentName(this, CustomDeviceAdminReceiver.class);
		mDevicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);

		if (!mDevicePolicyManager.isAdminActive(mAdminComponent)) {
			Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
			intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mAdminComponent);
			startActivityForResult(intent, REQUEST_ENABLE);
		} else {
			performLockScreen();
		}
		
		finish();
	}
	
	@Override
	protected void onPause() {
		if (isFinishing()) {
			overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
		}
		super.onPause();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == REQUEST_ENABLE) {
			performLockScreen();
		}
	}

	/**
	 * Perform lock screen.
	 */
	private void performLockScreen() {
		final PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
		final Handler handler = new Handler(getMainLooper());
		final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
		mTryNumber = 1;
		
		handler.post(new Runnable() {
			public void run() {
				if (powerManager.isScreenOn() && mTryNumber <= MAX_TRY_LOCK_NUMBER) {
					try {
						mDevicePolicyManager.lockNow();
					} catch (Exception e) {
						e.printStackTrace();
					}
					LogManager.infor(TAG, "lockNow");
					mTryNumber ++;
					handler.postDelayed(this, 500);
				} else {
					if (sharedPreferences.getBoolean(Constant.PREFERS_SETTING_ENABLE_VIBRATOR, false)) {
						Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
						v.vibrate(1000);
					}
					if (sharedPreferences.getBoolean(Constant.PREFERS_SETTING_BACKTOHOME, false)) {
						Intent startMain = new Intent(Intent.ACTION_MAIN);
						startMain.addCategory(Intent.CATEGORY_HOME);
						startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						startActivity(startMain);
					}
					if (sharedPreferences.getBoolean(Constant.PREFERS_SETTING_ENABLE_SOUND, false)) {
						MediaPlayer player = MediaPlayer.create(MainActivity.this, R.raw.lock);
						player.start();
						player.setOnCompletionListener(new OnCompletionListener() {
							
							@Override
							public void onCompletion(MediaPlayer mp) {
								mp.release();
							}
						});
					}
					finish();
				}
			}
		});
	}
}
